<template>
  <div class="weather-container">
    <div class="weather-content">
      <div class="location-info">
        <EnvironmentOutlined />
        <span class="location-text">烟台市</span>
      </div>
      <div class="weather-info">
        <component :is="weatherIcon" />
        <span class="weather-text">25°C {{ weather.text }}</span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, computed } from 'vue'
  import {
    EnvironmentOutlined,
    CloudOutlined,
    ThunderboltOutlined,
    CloudDownloadOutlined,
    CloudTwoTone,
  } from '@ant-design/icons-vue'
  import { message } from 'ant-design-vue'

  // 定义天气数据接口
  interface WeatherData {
    temp: number
    text: string
    code: number
  }

  // 初始化状态
  const location = ref('获取中...')
  const weather = ref<WeatherData>({
    temp: 0,
    text: '获取中...',
    code: 99,
  })

  // 根据天气状况选择图标
  const weatherIcon = computed(() => {
    const code = weather.value.code

    // 晴天
    if (code === 0 || code === 1 || code === 2) {
      return CloudTwoTone
    }
    // 多云
    else if (code === 3 || code === 4 || code === 5 || code === 6 || code === 7 || code === 8) {
      return CloudTwoTone
    }
    // 雨天
    else if (code >= 9 && code <= 18) {
      return CloudDownloadOutlined
    }
    // 雷雨
    else if (code >= 19 && code <= 25) {
      return ThunderboltOutlined
    }
    // 默认图标
    else {
      return CloudOutlined
    }
  })

  // 获取位置信息
  const getLocation = () => {
    return new Promise<{ city: string; province: string }>(resolve => {
      // 尝试使用浏览器地理位置API获取精确位置
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
          async position => {
            try {
              // 使用坐标获取城市信息（通过逆地理编码）
              const lat = position.coords.latitude
              const lng = position.coords.longitude

              // 使用高德地图逆地理编码API
              const response = await fetch(
                `https://restapi.amap.com/v3/geocode/regeo?key=3e9add7d50b0061d9baaf9eac165e5fe&location=${lng},${lat}&extensions=base`
              )
              const data = await response.json()

              if (data.status === '1' && data.regeocode && data.regeocode.addressComponent) {
                const addressComponent = data.regeocode.addressComponent
                resolve({
                  city: addressComponent.city || addressComponent.district || '北京市',
                  province: addressComponent.province || '北京',
                })
              } else {
                // 如果逆地理编码失败，回退到IP定位
                fallbackToIpLocation(resolve)
              }
            } catch (error) {
              console.error('逆地理编码失败:', error)
              // 如果出错，回退到IP定位
              fallbackToIpLocation(resolve)
            }
          },
          error => {
            console.error('获取地理位置失败:', error)
            // 如果获取位置失败，回退到IP定位
            fallbackToIpLocation(resolve)
          },
          {
            enableHighAccuracy: true,
            timeout: 5000,
            maximumAge: 0,
          }
        )
      } else {
        // 如果浏览器不支持地理位置API，回退到IP定位
        fallbackToIpLocation(resolve)
      }
    })
  }

  // IP定位回退函数
  const fallbackToIpLocation = (resolve: (value: { city: string; province: string }) => void) => {
    fetch('https://restapi.amap.com/v3/ip?key=3e9add7d50b0061d9baaf9eac165e5fe')
      .then(response => response.json())
      .then(data => {
        if (data.status === '1') {
          resolve({
            city: data.city || '北京市',
            province: data.province || '北京',
          })
        } else {
          resolve({
            city: '北京市',
            province: '北京',
          })
        }
      })
      .catch(error => {
        console.error('IP定位失败:', error)
        resolve({
          city: '北京市',
          province: '北京',
        })
      })
  }

  // 获取天气信息
  const getWeather = async (city: string) => {
    try {
      // 使用和风天气API
      const response = await fetch(
        `https://devapi.qweather.com/v7/weather/now?location=${city}&key=5d68d2a127064e7c936a7d2bc9cd4d45`
      )
      const data = await response.json()

      if (data.code === '200') {
        return {
          temp: parseInt(data.now.temp),
          text: data.now.text,
          code: parseInt(data.now.icon),
        }
      } else {
        // 返回默认值而不是抛出错误
        return {
          temp: 25,
          text: '多云转晴',
          code: 0,
        }
      }
    } catch (error) {
      console.error('获取天气失败:', error)
      // 返回默认值
      return {
        temp: 25,
        text: '晴',
        code: 0,
      }
    }
  }

  // 初始化
  onMounted(async () => {
    try {
      // 获取位置
      const locationData = await getLocation()
      // 只显示城市名称，不重复显示省份和城市
      location.value = locationData.city

      // 获取天气
      weather.value = await getWeather(locationData.city)
    } catch (error) {
      console.error('初始化天气组件失败:', error)
      message.error('获取天气信息失败')

      // 设置默认值
      location.value = '北京市'
      weather.value = {
        temp: 25,
        text: '晴',
        code: 0,
      }
    }
  })
</script>

<style scoped>
  .weather-container {
    display: flex;
    padding: 0 10px;
    margin-right: 20px; /* 增加右边距，远离头像 */
    border-right: 1px solid #f0f0f0;
    height: 50px;
    justify-content: center;
    align-items: center;
  }

  .weather-content {
    display: flex;
    flex-direction: row;
    align-items: center;
    gap: 20px; /* 增加间距 */
  }

  .location-info,
  .weather-info {
    display: flex;
    align-items: center;
    font-size: 14px; /* 增加字体大小 */
    color: #666;
  }

  .location-text,
  .weather-text {
    margin-left: 6px; /* 增加图标和文字的间距 */
    white-space: nowrap;
    font-weight: 500; /* 加粗字体 */
  }

  .weather-info {
    color: #1890ff;
  }
</style>
